package com.itany.springcloud.springcloudconsumer.controller;


import com.itany.springcloud.springcloudcommon.entity.User;
import com.itany.springcloud.springcloudcommon.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/users")
public class UserController {

    private static final String GLOBAL_URL="http://127.0.0.1:8080/users";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping
    public ResponseResult add(User user){

        MultiValueMap param=new LinkedMultiValueMap();
        param.add("username",user.getUsername());
        param.add("password",user.getPassword());

        return restTemplate.postForObject(GLOBAL_URL,param,ResponseResult.class);
    }

    @GetMapping
    public ResponseResult findAll(){
        return restTemplate.getForObject(GLOBAL_URL,ResponseResult.class);
    }

    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id){
        return restTemplate.getForObject(GLOBAL_URL+"/{id}",ResponseResult.class,id);
    }

    @DeleteMapping("/{id}")
    public ResponseResult remove(@PathVariable("id") Integer id){
        restTemplate.delete(GLOBAL_URL+"/{id}",id);
        return ResponseResult.success();
    }

    @PutMapping
    public ResponseResult modify(User user){
//        MultiValueMap param=new LinkedMultiValueMap();
//        param.add("id",user.getId());
//        param.add("username",user.getUsername());
//        param.add("password",user.getPassword());
//        restTemplate.put(GLOBAL_URL,param);
//        return ResponseResult.success();


//        HttpHeaders headers=new HttpHeaders();
//        headers.add("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE);
//
//        MultiValueMap param=new LinkedMultiValueMap();
//        param.add("id",user.getId());
//        param.add("username",user.getUsername());
//        param.add("password",user.getPassword());
//
//        HttpEntity<MultiValueMap<String,Object>> requestEntity=new HttpEntity<>(param,headers);
//
//        ResponseEntity<ResponseResult> responseEntity=restTemplate.exchange(GLOBAL_URL, HttpMethod.PUT,requestEntity,ResponseResult.class);
//        return responseEntity.getBody();


        String url=new StringBuffer()
                .append(GLOBAL_URL)
                .append("?id={id}")
                .append("&username={username}")
                .append("&password={password}")
                .toString();

        ResponseEntity<ResponseResult> responseEntity=restTemplate.exchange(url,HttpMethod.PUT,null,ResponseResult.class,user.getId(),user.getUsername(),user.getPassword());
        return responseEntity.getBody();


    }













}
